#ifndef _TEXTON_H
#define _TEXTON_H

#include <string>
#include <sstream>

using namespace std;

class Texton {
public:
	Texton() 
	{
		x = y = width = height = sum = 0;
		textonId = levelFound = -1;
		m_pTextonImage = NULL;
	}

	Texton(int _x, int _y, int _width, int _height, int _id, int _level, int _sum)
	{
		x = _x;
		y = _y;
		width = _width;
		height = _height;
		detectorId = _id;
		levelFound = _level;
		sum = _sum; 
		m_pTextonImage = NULL;
	}

	~Texton() 
	{
		
	}

	void SetImage(IplImage* pImage)
	{
		//if (m_pTextonImage)
		//	cvReleaseImage(&m_pTextonImage);
		m_pTextonImage = pImage;
	}

	IplImage* GetImage()
	{
		return m_pTextonImage;
	}
	
	CvPoint TopLeft() 
	{
		return cvPoint(x,y);
	}

	CvPoint BottomRight()
	{
		return cvPoint(x + width, y + height);
	}


	bool Intersects(const Texton* texton) const
    {
	if ((x > texton->x + texton->width) ||
		(x + width < texton->x) ||
		(y > texton->y + texton->height) ||
		(y + height < texton->y))
		{
			return false;
		}

	  return true;
    }

	bool IsFamily(int level, int _detectorId) const 
	{
		return (levelFound == level && detectorId == _detectorId);
	}

	void Scale(double fScale) {
		x = (int)(x * fScale);
		y = (int)(y * fScale);
		width = (int)(width * fScale);
		height = (int)(height * fScale);
	}

	bool IsSimilar(Texton* texton) const;
	void MarkTexton(IplImage* inputImage, CvScalar color);

	void Save(const string& strPath )
	{
		if (m_pTextonImage == NULL)
		{
			printf("Could not save texton, image is null\n");
			return;
		}
		std::string filePath;
		std::stringstream out;
		out << strPath;
		out << "texton_";
		out << detectorId;
		out << "_";
		out << levelFound;
		out << "_";
		out << textonId;

		out << ".bmp";

		filePath = out.str();

		cvSaveImage(filePath.c_str(), m_pTextonImage);
	}

	int x,y;			//location in the pattern
	int width, height;  // ...
	int detectorId;
	int textonId;		//...
	int levelFound;		//the pyramid level it was found in
	int sum;			//the SSD (distance)

	friend bool operator<(const Texton& t1,const Texton& t2);
protected:

	IplImage* m_pTextonImage;
};

#endif